package com.bianmaba;

import com.bianmaba.beans.datacollection.TaskInstance;
import com.bianmaba.commons.data.jpa.domain.request.Condition;
import com.bianmaba.dc.bean.TaskStatus;
import com.bianmaba.services.datacollection.ExecuteLogRecorder;
import com.bianmaba.services.datacollection.ITaskInstanceService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;

@Component
@Log4j2
public class StartupRunner implements CommandLineRunner {
    @Autowired
    private ExecuteLogRecorder logWriter;
    @Autowired
    private ExecutorService executorService;

    @Autowired
    private ITaskInstanceService taskInstanceService;

    @Override
    public void run(String... args) throws Exception {
        log.info("准备运行日志写入器...");
        executorService.execute(logWriter);

        log.info("准备恢复采集任务状态监听...");
        Condition condition = Condition.ofOr().addOr("status", TaskStatus.WAIT.getIndex()).addOr("status", TaskStatus.RUNNING.getIndex());
        List<TaskInstance> instances = taskInstanceService.queryToList(condition);
        if (!instances.isEmpty()) {
            for (TaskInstance instance : instances) {
                taskInstanceService.startStatusCheck(instance.getId());
            }
            log.info(String.format("共恢复%s个任务监听。", instances.size()));
        } else {
            log.info("无采集任务状态需要监听。");
        }
    }
}
